﻿<Cmdlet(VerbsLifecycle.Invoke, "SqlQuery")>
Public Class InvokeSqlQuery
    Inherits PSCmdlet

    <Parameter(Mandatory:=True, Position:=1)>
    Public Property Query As String
    <Parameter(Position:=2, ValueFromPipeline:=True)>
    Public Property Parameters As Hashtable
    <Parameter>
    Public Property ConnectionName As String = "Default"
    <Parameter>
    Public Property Stream As SwitchParameter

    <Parameter>
    Public Property CommandTimeout As Integer = -1

    Protected Overrides Sub ProcessRecord()
        MyBase.ProcessRecord()

        If Not DBInfo.Connections.ContainsKey(Me.ConnectionName) Then
            WriteWarning(DBInfo.NoConnection(Me.ConnectionName))
            Exit Sub
        End If

        DBInfo.ProcessHashTable(Me.Parameters)
        DBInfo.Connections(Me.ConnectionName).ClearMessages()

        If Stream.IsPresent Then
            Using cmd As IDbCommand = DBInfo.Connections(Me.ConnectionName).GetCommand(Query, CommandTimeout, Parameters)
                Using dr As IDataReader = cmd.ExecuteReader()
                    Dim data As Generic.List(Of DBInfo.Map) = DBInfo.Connections(Me.ConnectionName).CreateMap(dr.GetSchemaTable)
                    While dr.Read
                        WriteObject(DBInfo.ConvertToPSObject(dr, data))
                    End While
                End Using
            End Using
        Else
            Dim ds As DataSet
            Using cmd As IDbCommand = DBInfo.Connections(Me.ConnectionName).GetCommand(Query, CommandTimeout, Parameters)
                ds = DBInfo.Connections(Me.ConnectionName).GetDataSet(cmd)
            End Using
            If ds.Tables.Count = 1 Then
                WriteObject(ds.Tables(0).Rows, True)
            Else
                WriteObject(ds.Tables, True)
            End If
        End If
    End Sub

End Class